from django.shortcuts import render, redirect
from goods.models import GoodsCategory, GoodsInfo
from cart.models import CartList, OrderGoods, OrderInfo
from django.db.models import Max, Min, Count, Sum, Avg
from datetime import datetime


# Create your views here.
#  跳转到购物车页面
def cart(re):
    cart_goods_list = []  # 商品分类列表
    categories = GoodsCategory.objects.all()  # 获取商品分类
    for cag in categories:
        cart_goods_list.append(cag)
    # 查詢数据库中购物车信息
    cart_goods = CartList.objects.all()  # 获取购物车中的商品信息商品数量和商品id
    cart_goods_lists = []
    cart_goods_nums = []
    # 通过goods_id 找goods表中的商品数据 封装到cart_goods_lists中
    for item in cart_goods:
        goods_info = GoodsInfo.objects.filter(id=item.goods_id)
        cart_goods_nums.append(item.goods_nums)
        cart_goods_lists.append(goods_info)
    # 将对应的商品数量追加到对应的商品中 封装成最终的数据
    for index in range(len(cart_goods_lists)):
        cart_goods_lists[index].num = cart_goods_nums[index]

        # 计算总金额
    total_money = 0  # 总金额
    before_discount = 0  # 折扣前
    if cart_goods.count() > 0:
        discount = 10
        freight = 10  # 运费
    else:
        freight = 0  # 运费
        discount = 0  # 折扣
    price_list = []  # 商品价格
    for indexs in range(len(cart_goods_lists)):
        for items in cart_goods_lists[indexs]:
            price_list.append(items.goods_price)

    for i in range(len(price_list)):
        before_discount += price_list[i] * cart_goods_nums[i]
    total_money = before_discount - discount + freight
    # 购物车商品总数量
    total_nums = CartList.objects.aggregate(total_nums=Count('*'))
    total_nums = total_nums['total_nums']

    return render(re, 'cart.html', {
        'cart_goods_list': cart_goods_list,
        'cart_goods': cart_goods,
        'cart_goods_lists': cart_goods_lists,
        "total_nums": total_nums,
        "before_discount": before_discount,
        "total_money": total_money,
        "freight": freight,
        "discount": discount
    })


#    添加购物车
def add(request, id=1, num=1):
    msg = '操作失败！'
    sc = CartList.objects.filter(goods_id=id)
    if sc.count() > 0:
        obj = CartList.objects.get(goods_id=id)
        obj.goods_nums = num
        obj.save()
        msg = '操作成功！'
    else:
        CartList.objects.create(goods_id=id, goods_nums=num)
        msg = '操作成功！'
    return render(request, 'message.html', {
        "msg": msg
    })


# 加减1
def change_one(request, id=1, num=1):
    if num < 1:
        num = 1
    obj = CartList.objects.get(goods_id=id)
    obj.goods_nums = num
    obj.save()
    msg = '操作成功！'
    cart_goods_list = []  # 商品分类列表
    categories = GoodsCategory.objects.all()  # 获取商品分类
    for cag in categories:
        cart_goods_list.append(cag)
    # 查詢数据库中购物车信息
    cart_goods = CartList.objects.all()  # 获取购物车中的商品信息商品数量和商品id
    cart_goods_lists = []
    cart_goods_nums = []
    # 通过goods_id 找goods表中的商品数据 封装到cart_goods_lists中
    for item in cart_goods:
        goods_info = GoodsInfo.objects.filter(id=item.goods_id)
        cart_goods_nums.append(item.goods_nums)
        cart_goods_lists.append(goods_info)

    for index in range(len(cart_goods_lists)):
        cart_goods_lists[index].num = cart_goods_nums[index]  # 将对应的商品数量追加到对应的商品中 封装成最终的数据
        # total_money += cart_goods_lists[index].goods_price * cart_goods_nums[index]
        # 计算总金额
    total_money = 0  # 总金额
    before_discount = 0  # 折扣前
    if cart_goods.count() > 0:
        discount = 10
        freight = 10  # 运费
    else:
        freight = 0  # 运费
        discount = 0  # 折扣
    price_list = []  # 商品价格
    for indexs in range(len(cart_goods_lists)):
        for items in cart_goods_lists[indexs]:
            price_list.append(items.goods_price)

    for i in range(len(price_list)):
        before_discount += price_list[i] * cart_goods_nums[i]
    total_money = before_discount - discount + freight
    # 购物车商品总数量
    total_nums = CartList.objects.aggregate(total_nums=Count('*'))
    total_nums = total_nums['total_nums']

    return render(request, "cart.html", {
        'cart_goods_list': cart_goods_list,
        'cart_goods': cart_goods,
        'cart_goods_lists': cart_goods_lists,
        "total_nums": total_nums,
        "before_discount": before_discount,
        "total_money": total_money,
        "freight": freight,
        "discount": discount
    })  # 重定向


#    删除购物车
def delete(request, id=1):
    CartList.objects.filter(goods_id=id).delete()
    msg = '操作成功！'
    return render(request, 'message.html', {
        "msg": msg
    })


#    修改购物车
# def edit(request, id=1):
#     obj = CartList.objects.get(goods_id=id)
#     obj.goods_nums = num
#     obj.save()
#     msg = '操作成功！'
#     return render(request, 'message.html', {
#         "msg": msg
#     })


#    清空购物车
def clear(request):
    CartList.objects.all().delete()
    msg = '操作成功！'
    return render(request, 'message.html', {
        "msg": msg
    })


# 生成订单页面
def order(request):
    cart_goods_list = []  # 商品分类列表
    categories = GoodsCategory.objects.all()  # 获取商品分类
    for cag in categories:
        cart_goods_list.append(cag)
    # 查詢数据库中购物车信息
    cart_goods = CartList.objects.all()  # 获取购物车中的商品信息商品数量和商品id
    cart_goods_lists = []
    cart_goods_nums = []
    # 通过goods_id 找goods表中的商品数据 封装到cart_goods_lists中
    for item in cart_goods:
        goods_info = GoodsInfo.objects.filter(id=item.goods_id)
        cart_goods_nums.append(item.goods_nums)
        cart_goods_lists.append(goods_info)

    for index in range(len(cart_goods_lists)):
        cart_goods_lists[index].num = cart_goods_nums[index]  # 将对应的商品数量追加到对应的商品中 封装成最终的数据
        # total_money += cart_goods_lists[index].goods_price * cart_goods_nums[index]
        # 计算总金额
    total_money = 0  # 总金额
    before_discount = 0  # 折扣前
    if cart_goods.count() > 0:
        discount = 10
        freight = 10  # 运费
    else:
        freight = 0  # 运费
        discount = 0  # 折扣
    price_list = []  # 商品价格
    for indexs in range(len(cart_goods_lists)):
        for items in cart_goods_lists[indexs]:
            price_list.append(items.goods_price)

    for i in range(len(price_list)):
        before_discount += price_list[i] * cart_goods_nums[i]
    total_money = before_discount - discount + freight
    # 购物车商品总数量
    total_nums = CartList.objects.aggregate(total_nums=Count('*'))
    total_nums = total_nums['total_nums']

    return render(request, 'orderlist.html', {
        'cart_goods_list': cart_goods_list,
        'cart_goods': cart_goods,
        'cart_goods_lists': cart_goods_lists,
        "total_nums": total_nums,
        "before_discount": before_discount,
        "total_money": total_money,
        "freight": freight,
        "discount": discount
    })


# 随机生成订单号
def set_flow():
    base_code = datetime.now().strftime('%Y%m%d%H%M%S')
    oreder_list = []
    count = 1
    while True:
        if count > 1:
            break
        count_str = str(count).zfill(8)
        oreder_list.append(base_code + count_str)
        count += 1
    return oreder_list[0]


# 提交订单
def order_submit(request):
    order_ids = set_flow()  # 随机生产订单编号
    if request.method == "POST":
        order_recv = request.POST['order_recv']
        order_addr = request.POST['order_addr']
        order_tele = request.POST['order_tele']
        order_extra = request.POST['order_extra']
        order_fee = request.POST['freight']
        # 封装数据插入封装数据插入cart_orderinfo表
        OrderInfo.objects.create(
            order_id=order_ids,
            order_recv=order_recv,
            order_addr=order_addr,
            order_tele=order_tele,
            order_extra=order_extra,
            order_fee=order_fee,
            order_status=1
        )
        cart_goods = CartList.objects.all()
        cart_goods_nums = []
        cart_goods_id = []
        for item in cart_goods:
            cart_goods_nums.append(item.goods_nums)
            cart_goods_id.append(item.goods_id)

        # 封装数据插入cart_ordergoods表
        d = OrderInfo.objects.get(order_id=order_ids)
        print(len(cart_goods_id))
        for i in range(len(cart_goods_id)):
            OrderGoods.objects.create(
                goods_nums=cart_goods_nums[i],
                goods_info_id=cart_goods_id[i],
                goods_order_id=d.order_id,
            )
    # 生产订单提交成功页面数据
    info = OrderInfo.objects.filter(order_id=order_ids)  # 订单联系人相关信息
    goods = OrderGoods.objects.filter(goods_order_id=order_ids)
    total_nums = goods.count()
    # 获取订单商品的信息
    cart_goods_lists = []  # 订单信息列表
    # 购物车商品总数量
    total_nums = OrderGoods.objects.filter(goods_order_id=order_ids).aggregate(total_nums=Count('*'))
    total_nums = total_nums['total_nums']
    for item in goods:
        goods_info = GoodsInfo.objects.filter(id=item.goods_info_id)
        cart_goods_nums.append(item.goods_nums)
        cart_goods_lists.append(goods_info)

    for index in range(len(cart_goods_lists)):
        cart_goods_lists[index].num = cart_goods_nums[index]  # 将对应的商品数量追加到对应的商品中 封装成最终的数据
    before_discount = 0
    price_list = []  # 商品价格
    for indexs in range(len(cart_goods_lists)):
        for items in cart_goods_lists[indexs]:
            price_list.append(items.goods_price)

    for i in range(len(price_list)):
        before_discount += price_list[i] * cart_goods_nums[i]

    discount = 10
    total_money = 0
    order_fee = 0
    for i in info:
        order_fee = i.order_fee
        print(i.order_fee)
    total_money = order_fee - discount+before_discount
    # 清空 cart_cartlist表
    CartList.objects.all().delete()
    return render(request, 'orderSucess.html', {
        "info": info,
        "total_nums": total_nums,
        "cart_goods_lists": cart_goods_lists,
        "before_discount": before_discount,
        "discount": discount,
        "total_money": total_money,
        "order_fee": order_fee
    })
